package com.lh.oauth.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.springframework.stereotype.Component;

import com.lh.entity.OpenUser;
import com.lh.entity.OpenUser.OpenUserType;
import com.lh.oauth.OAuth;
import com.lh.util.Configuration;
import com.lh.util.HttpUtil;

/**
 * @author liuhui
 * @version 1.0
 * @date 2013-4-29 下午4:54:21
 */
@Component
public class SinaOAuth implements OAuth {
	
	private static final String APP_KEY = "1764719121" ;
	private static final String App_Sercet = "78ba94337a36d3049503f2c36e7f36e2" ;
	private static final String AUTHORIZE_URL = "https://api.weibo.com/oauth2/authorize" ;
	private static final String TOKEN_URL = "https://api.weibo.com/oauth2/access_token" ;
	private static final String USER_INFO_URL = "https://api.weibo.com/2/users/show.json" ;
	private static final String ADD_WB_URL = "https://api.weibo.com/2/statuses/update.json" ;
	
	@Override
	public String genLoginUrl() {
		StringBuilder queryString = new StringBuilder();
		queryString.append("client_id=").append(APP_KEY).append("&scope=follow_app_official_microblog&redirect_uri=").append(CALLBACK_URL).append("/").append( OpenUserType.SINA.getValue());
		return AUTHORIZE_URL+"?" + queryString.toString() ;
	}

	@Override
	public OpenUser obtainOpenUser(String code) {
		Map<String, String> ps = new HashMap<String, String>();
		ps.put("client_id", APP_KEY);
		ps.put("client_secret", App_Sercet);
		ps.put("grant_type", "authorization_code");
		ps.put("code", code);
		ps.put("redirect_uri",CALLBACK_URL+"/" + OpenUserType.SINA.getValue());
		String accessTokenString = HttpUtil.post(TOKEN_URL , ps);
		JSONObject jsonObject = (JSONObject)JSONSerializer.toJSON(accessTokenString);
		String accessToken = jsonObject.getString("access_token");
		String openid = jsonObject.getString("uid");
		ps.clear();
		ps.put("access_token", accessToken);
		ps.put("uid", openid);
		String userInfo = HttpUtil.get(USER_INFO_URL , ps );
		JSONObject json = (JSONObject) JSONSerializer.toJSON(userInfo);
		OpenUser ou = new OpenUser();
		ou.setCreateTime(new Date());
		ou.setNickname(json.getString("screen_name"));
		ou.setOpenid(openid);
		ou.setUserInfo(json.toString());
		ou.setAccessToken(accessToken);
		ou.setType(OpenUserType.SINA.getValue());
		return ou ;
	}

	public void shareInfo(OpenUser openUser) {
		Map<String, String> ps = new HashMap<String, String>();
		ps.put("access_token", openUser.getAccessToken());
		ps.put("status", Configuration.OPEN_LOGIN_SHAREMSG + ">>http://www.kaijingbao.com @凯晶堡商城 ");
		String rs = HttpUtil.post(ADD_WB_URL , ps );
		System.out.println(rs);
	}

}
